import { Component, OnInit } from '@angular/core';
// 当作一个服务
import {HttpClient, HttpHeaders} from '@angular/common/http';

// 使用服务里面的axios获取数据
import { HttpServiceService } from '../../services/http-service.service';

@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {

  public list = [];

  constructor(public http: HttpClient, public httpService: HttpServiceService) { }

  ngOnInit(): void {
  }

  getData() {
    // 服务器必须允许跨域
    const api = 'http://a.itying.com/api/productList';

    this.http.get(api).subscribe((res: any) => {
      // console.log(res);
      this.list = res.result;
    });
  }

  doLogin() {
    // 手动设置请求类型
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json' })
    };

    const api = 'http://127.0.0.1:3000/doLogin';
    this.http.post(api, { username: '张三', age: '20'}, httpOptions).subscribe(response => {
      console.log(response);
    });
  }

  getJsonp() {
    // Jsonp请求 服务器必须得支持jsonp   jsonp请求带回调函数  可以跨域的问题
    /**
     * http://a.itying.com/api/productList?callback-xxx
     * http://a.itying.com/api/productlist?cb=xxx
     */

    const api = 'http://a.itying.com/api/productlist';
    this.http.jsonp(api, 'callback').subscribe(res => {
      console.log(res);
    });
  }

  getAxiosData() {
    const api = 'http://a.itying.com/api/productlist';
    this.httpService.axiosGet(api)
      .then(data => {
        console.log(data);
      });
  }
}
